package com.cn.auth.config.custom;

import com.cn.auth.config.JwtTokenEnhancerConfig;
import com.cn.auth.config.custom.sms.SmsAuthenticationKeyGenerator;
import com.cn.auth.redis.RedisConstant;
import com.cn.auth.redis.strategy.FastjsonRedisTokenStoreSerializationStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @author: zhoujunming
 * @Description: 自定义token store
 * @date: 2024/1/4 14:33
 * @email: zhoujunming@bluemoon.com.cn
 */
@Configuration
public class CustomTokenStoreConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Resource
    private JwtAccessTokenConverter accessTokenConverter;

    @Resource
    JwtTokenEnhancerConfig jwtTokenEnhancerConfig;

    /**
     * 默认是InMemoryTokenStore
     * 也可以采用JdbcTokenStore，JwtTokenStore。
     *
     * @return
     */
    @Bean("commonTokenStore")
    public TokenStore commonTokenStore(){
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        //缓存redis数据序列化
        redisTokenStore.setSerializationStrategy(new FastjsonRedisTokenStoreSerializationStrategy());
        //缓存redis数据序列化
        redisTokenStore.setSerializationStrategy(new FastjsonRedisTokenStoreSerializationStrategy());
        //前缀
        redisTokenStore.setPrefix(RedisConstant.AUTH_TOKEN.getKey());
        return redisTokenStore;
    }

    /**
     * 设置token存储，这一点配置要与授权服务器相一致
     */
    @Bean("smsTokenStore")
    public TokenStore smsTokenStore() {
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        //缓存redis数据序列化
        redisTokenStore.setSerializationStrategy(new FastjsonRedisTokenStoreSerializationStrategy());
        //前缀
        redisTokenStore.setPrefix(RedisConstant.AUTH_TOKEN.getKey());
        //配置短信
        redisTokenStore.setAuthenticationKeyGenerator(new SmsAuthenticationKeyGenerator());
        return redisTokenStore;
    }

    @Bean("smsTokenEnhancerChain")
    public TokenEnhancerChain smsTokenEnhancerChain(){
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtTokenEnhancerConfig,accessTokenConverter));
        return tokenEnhancerChain;
    }
}
